<template>
  <div style="width: 100%; height: 100%; padding: 0">
    <div class="page-content">
      <a-card style="width: 100%; height: 100%" v-if="!showDetail">
        <div class="header">
          <Condition
            :condition="condition"
            :btns="['search', 'reset']"
            @search="searchHandle"
            @reset="reset"
          />
          <span> 共筛选出 {{ pagination.total }} 条数据 </span>
        </div>
        <div class="main">
          <a-table
            class="table"
            size="small"
            :loading="loading"
            :dataSource="List"
            :columns="columns"
            :pagination="pagination"
            @change="paginationChange"
            :sticky="{ offsetHeader: 0 }"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex == 'no'">
                {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
              </template>
              <template v-else-if="column.dataIndex == 'patName'">
                <span class="patName" @click="patientInfoHandle(record)"
                  >{{ record.patName }} {{ record.gender }} {{ record.age }}</span
                >
              </template>
              <template v-else-if="column.dataIndex == 'expiredTime'">
                <span v-if="record.expiredTime">
                  {{ record.buyTime }} ~ {{ record.expiredTime }}
                </span>
                <span v-else style="color: #3491fa">
                  <ExclamationCircleFilled two-tone-color="#3491FA" />
                  未生效
                </span>
              </template>
              <!-- <template v-else-if="column.dataIndex == 'reportState'">
                  <span style="color: #00b42a" v-if="record.reportState == 1">
                    <CheckCircleFilled two-tone-color="#00B42A" />
                    已生成
                  </span>
                  <span style="color: #ff7d00" v-if="record.reportState == 0">
                    <ExclamationCircleFilled two-tone-color="#ff7d00" />
                    未生成
                  </span>
                </template> -->
              <template v-else-if="column.dataIndex === 'action'">
                <p class="chat">
                  <span v-if="record.lastMsgSendTime" class="ant-badge" />
                  <a-button type="link" @click="singleChat(record)">群聊</a-button>
                </p>
              </template>
            </template>
          </a-table>
        </div>
      </a-card>
      <PatientInfo ref="patientInfoRef" v-else @close="goBack" />
      <a-modal
        width="720px"
        height="640px"
        v-model:open="modalOpen"
        class="danliao"
        :footer="null"
        title="群聊"
        :maskClosable="true"
      >
        <div class="modalChat">
          <iframe
            v-if="modalShow"
            class="content"
            :src="chatSrc"
            frameborder="0"
            style="width: 100%; height: calc(100% - 1px)"
          />
          <a-empty class="empty" v-else />
        </div>
      </a-modal>
    </div>
  </div>
</template>
<script lang="ts" setup>
import Condition from '@/components/ConditionSearch/index.vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { counselingPage } from '@/api/patientMana/index.ts'
import { getIMAccountGroup } from '@/api/index'
import { getManagePathList, counselingRead } from '@/api/healthManaWorkbench/index'
// import PatientInfo from './patientInfo.vue'
import PatientInfo from '@/views/examinatePatients/patientInfo.vue'
import { useDict } from './components/getDict'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'
import { CheckCircleFilled, ExclamationCircleFilled } from '@ant-design/icons-vue'
import { saveIMMsg } from '@/api/imMsg'
import store from '@/store'
const manaPathData = ref([])

const route = useRoute()
const showDetail = ref(false)
const loading = ref(false)
const modalOpen = ref(false)
const modalShow = ref(false)
const chatSrc = ref('')
const List = ref<any[]>([])
const condition = ref([
  {
    title: '',
    dataIndex: 'keywords',
    type: 'input',
    value: '',
    placeholder: '请输入姓名/手机号/证件号',
    style: {
      width: '225px'
    }
  },
  {
    title: '已配置管理路径',
    dataIndex: 'pathId',
    type: 'select',
    data: manaPathData,
    value: undefined,
    placeholder: '请选择管理路径',
    showSearch: true
  }
])
const columns = ref<any[]>([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: 80
  },
  {
    title: '账号',
    dataIndex: 'userPhone',
    key: 'userPhone',
    align: 'left'
  },
  {
    title: '就诊人',
    dataIndex: 'patName',
    key: 'patName',
    align: 'left'
  },
  {
    title: '证件号',
    dataIndex: 'idNo',
    key: 'idNo',
    align: 'left'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'left'
  },
  {
    title: '服务包',
    dataIndex: 'tradeName',
    key: 'tradeName',
    align: 'left'
  },
  {
    title: '管理路径',
    dataIndex: 'pathName',
    key: 'pathName',
    align: 'left'
  },
  {
    title: '服务包有效期',
    dataIndex: 'expiredTime',
    key: 'expiredTime',
    align: 'left',
    width: 160
  },
  {
    title: '负责人',
    dataIndex: 'managerName',
    key: 'managerName',
    align: 'left',
    width: 80
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: 100
  }
])
const pagination = ref<any>({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true
})
const paginationChange = (page: any) => {
  pagination.value = { ...page }
  loading.value = true
  getDataList()
}
const getDataList = () => {
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0 || v.value === false) {
      if (v.dataIndex == 'visitTime') {
        return Object.assign(c, {
          begin: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD HH:mm:00') : '',
          end: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD HH:mm:00') : ''
        })
      } else {
        return Object.assign(c, { [v.dataIndex]: v.value })
      }
    } else {
      return c
    }
  }, {})
  counselingPage({
    ...obj,
    page: pagination.value.current,
    limit: pagination.value.pageSize,
    diseaseType: 'weightLose'
  })
    .then((res) => {
      List.value = res.data.list
      pagination.value.total = res.data.total
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
onMounted(() => {
  if (route.query && route.query.type) {
    showDetail.value = true
    nextTick(() => {
      patientInfoRef.value.initRouterInfo(route.query)
    })
  }

  loading.value = true
  getDataList()
  getManaPath()

  window.addEventListener('message', (e) => {
    saveMsg(e.data)
  })
})

const saveMsg = (imData: any) => {
  if (imData.conversationType == 2) {
    let contType: any = ''
    let contString: any = ''
    switch (imData.messageType) {
      case 0:
        contType = 'text'
        contString = imData.text
        break
      case 1:
        contType = 'pic'
        contString = imData.attachment.url
        break
      default:
        contType = 'text'
        contString = imData.text
        break
    }
    const params = {
      senderUserType: 'manage',
      sender: healthData.value.manager,
      receiver: healthData.value.empi,
      content: contString,
      dialogueId: imData.conversationId,
      messageType: 'group',
      contentType: contType
    }
    // console.log('params', params)

    saveIMMsg(params).then(() => {
      console.log('保存成功')
    })
  }
}

const patientInfoRef = ref()
const patientInfoHandle = (data) => {
  showDetail.value = true
  nextTick(() => {
    patientInfoRef.value.init(data)
  })
}

const searchHandle = () => {
  pagination.value.current = 1
  loading.value = true
  getDataList()
}
const reset = () => {
  pagination.value.current = 1
  pagination.value.pageSize = 10
  condition.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else {
      v.value = ''
    }
  })
  loading.value = true
  getDataList()
  getManaPath()
}

const goBack = () => {
  showDetail.value = false
  loading.value = true
  getDataList()
}
const healthData = ref()
const singleChat = (item) => {
  healthData.value = item
  counselingRead({ id: item.id }).then((res) => {
    getDataList()
  })
  modalOpen.value = true
  const base = store.userStore.IMUrl
  // const appkey = '38bc2cc3c1383f7d6d45014594232b11'
  getIMAccountGroup().then((res) => {
    if (res.data) {
      modalShow.value = true
      chatSrc.value = `${base}?appkey=${res.data.appId}&account=${res.data.accid}&token=${res.data.token}&type=TeamChat&targetId=${res.data.accid}|2|${item.managerImaccid}`
      console.log(chatSrc.value)
    } else {
      modalShow.value = false
    }
  })
}
const getManaPath = () => {
  getManagePathList({
    page: 1,
    limit: 9999,
    diseaseType: 'weightLose'
  }).then((res) => {
    res.data.list.map((item) => {
      item.label = item.managePathName
      item.value = item.id
    })
    manaPathData.value = res.data.list
  })
}
</script>
<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
}

.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;

  .table {
    .patName {
      color: #1677ff;

      &:hover {
        cursor: pointer;
        opacity: 0.7;
      }
    }

    .chat {
      position: relative;
      display: inline-block;
      margin: 0;

      .ant-badge {
        position: absolute;
        top: 0;
        left: 25px;
        z-index: 1;
        display: block;
        width: 10px;
        height: 10px;
        background: #fa7117;
        border-radius: 10px;
      }
    }
  }
}

.modalChat {
  position: relative;
  width: 100%;
  height: 450px;

  .empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
<style>
.danliao .ant-modal-body {
  background: #f6f8fa;
}

.danliao .ant-modal-header {
  margin-bottom: 0 !important;
}

.danliao .ant-modal-header .ant-modal-title {
  color: #fff;
}
</style>
